<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>对角线遍历</title>
</head>

<body>
  <script>
    var findDiagonalOrder = function (mat) {
      const ans = []
      const row = mat.length
      const col = mat[0].length
      //循环轮次
      const turn = row + col - 1
      //变换数组
      const change = [[-1, 1], [1, -1]]
      let nowX = 0, nowY = 0
      for (let i = 0; i < turn; i++) {
        //本轮次在边界内的遍历
        while (nowX >= 0 && nowX < row && nowY >= 0 && nowY < col) {
          ans.push(mat[nowX][nowY])
          nowX += change[i % 2][0]
          nowY += change[i % 2][1]
        }
        //将位置返回到即将越界的位置
        nowX -= change[i % 2][0]
        nowY -= change[i % 2][1]
        //奇数轮次 -> 斜向下 3-2情况
        if (i % 2)
          if ((nowX + 1) < row)
            nowX += 1 //下边可行
          else
            nowY += 1 //下边不可行

        //偶数轮次 -> 斜向上 3-1情况
        else
          if ((nowY + 1) < col)
            nowY += 1 //右边可行
          else
            nowX += 1 //右边不可行

      }
      return ans
    }
    console.log(findDiagonalOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
  </script>
</body>

</html>